package com.shujia.jinjie;

import com.shujia.exceptions.RedisKeyNotFoundException;
import com.shujia.utils.HbaseUtil;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Scanner;

/**
 *  借助redis来构建hbase表的列值与行键的映射关系，作为二级索引表
 */
public class HbaseIndexWithRedis {
    public static void main(String[] args) throws Exception{
//        createIndexToRedisWithName();

        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要查询班级的学生姓名: ");
        String name = sc.next();

        //查询农星泽所在的班级

        String clazz = selectClazzWithName(name);
        System.out.println("该学生所在班级为："+clazz);

    }

    public static String selectClazzWithName(String name) throws Exception{
        //先查询redis，得到学号后再查hbase
        //创建redis的连接对象
        Jedis jedis = new Jedis("192.168.44.100", 7000);
        String clazz = null;

        try {
            String id = jedis.get(name);
            //再根据学号查班级这一列
            Table students = HbaseUtil.getOneTable("students");
            Result result = students.get(new Get(Bytes.toBytes(id)));
            clazz =  Bytes.toString(result.getValue(Bytes.toBytes("info"),Bytes.toBytes("clazz")));
        }catch (Exception e){
            try {
                throw new RedisKeyNotFoundException("redis中没有该学生的姓名作为键");
            } catch (RedisKeyNotFoundException ex) {
                ex.printStackTrace();
            }
        }

        return clazz;
    }

    public static void createIndexToRedisWithName() throws Exception{
        Table students = HbaseUtil.getOneTable("students");
        Scan scan = new Scan();
        ResultScanner resultScanner = students.getScanner(scan);

        //创建redis的连接对象
        Jedis jedis = new Jedis("192.168.44.100", 7000);

        for (Result result : resultScanner) {
            //取出姓名和学号
            String id = Bytes.toString(result.getRow());
            String name = Bytes.toString(result.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")));

            //添加到redis中
            jedis.set(name,id);
        }
        //释放资源
        jedis.close();

    }
}
